<?php

namespace component\extend\sparkTextAI;

use component\extend\IaiTextModel;
use GuzzleHttp\Client;
use Noodlehaus\Config;

/**
 * 星火AI 文本模型

 */
class Index implements IaiTextModel
{
    public function getRemainderToken() {}

    public function talk(string $content, string $userrole = 'user')
    {
        $config = Config::load(__DIR__ .  '/config.ini');
        $config = $config['value'];
        $client = new Client();
        $response = $client->request('POST', 'https://spark-api-open.xf-yun.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $config['APIPassword'],
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'model' => $config['MODEL'],
                'messages' => [
                    [
                        'role' => $userrole,
                        'content' => $content
                    ]
                ],

            ]  // 这里会自动将数组转换为 JSON 字符串，并设置正确的 Content-Type
        ]);
        $body = $response->getBody();

        $data = json_decode($body, true);

        if (isset($data['code']) && $data['code'] == 0) {
            return [
                'raw' => $data,
                'content' => $data['choices'][0]['message']['content'],

            ];
        }
    }
}
